import threading
import time
from queue import Queue


class StoppableThread(threading.Thread):
    """可停止的线程基类"""

    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()
        self.daemon = True

    def stop(self):
        """停止线程"""
        self._stop_event.set()

    def stopped(self):
        """检查线程是否已停止"""
        return self._stop_event.is_set()


class PollingThread(StoppableThread):
    """Modbus轮询线程"""

    def __init__(self, modbus_manager, interval=1.0):
        super().__init__()
        self.modbus_manager = modbus_manager
        self.interval = interval

    def run(self):
        """线程主循环"""
        logging.info("轮询线程启动")

        while not self.stopped():
            try:
                # 执行轮询逻辑
                self.modbus_manager.poll_registers()

                # 等待下一次轮询
                time.sleep(self.interval)
            except Exception as e:
                logging.error(f"轮询过程中发生错误: {str(e)}")
                time.sleep(2)  # 错误后稍作等待

        logging.info("轮询线程停止")